import hashlib
import json
import os
from pathlib import Path
from typing import Dict, List, Optional
from lxml import etree
import requests
# from openai import OpenAI
from deal_result import load_json_result, write_result_excel_v2


class DeepSeekCodeAnalyzer:
    def __init__(self):
        self.api_key = 'sk-b6eb6b5c93884e5aa2676e1e0d60d620'
        self.api_url = "https://api.deepseek.com/v1/"
        self.message = []
        self.cache_dir = Path('.code_cache')
        self.sort_txt_path = './.code_cache/sort.txt'
        # 先删除sort.txt
        try:
            os.remove(self.sort_txt_path)
        except FileNotFoundError:
            pass
        # 然后新建目录
        # self.cache_dir.mkdir(exist_ok=True)
        self.client = OpenAI(api_key=self.api_key, base_url=self.api_url)

    def analyze_html_file(self, html_file: str, article_url, product, name) -> Dict:
        """分析HTML文件"""
        cache_key = self._generate_cache_key(article_url)
        # 写入sort.txt后续按序号读取json文件
        with open(self.sort_txt_path, 'a', encoding='utf-8')as f:
            f.write(cache_key + '.json\n')

        with open(html_file, 'r', encoding='utf-8') as f:
            html = f.read()
            self.first_analyzer(article_url)
            result = self.second_analyzer(html, article_url)
            result['类型'] = product
            result['文章名称'] = name
            self.save_result_to_json(cache_key, result)
        return result

    def analyze_md_content(self, md_content, article_url, product, name):
        """分析MarkDown"""
        cache_key = self._generate_cache_key(article_url)
        # 写入sort.txt后续按序号读取json文件
        with open(self.sort_txt_path, 'a', encoding='utf-8') as f:
            f.write(cache_key + '.json\n')
        self.first_analyzer(article_url)
        result = self.second_analyzer(md_content, article_url)
        result['类型'] = product
        result['文章名称'] = name
        self.save_result_to_json(cache_key, result)

        return result

    def _generate_cache_key(self, url: str) -> str:
        """生成缓存文件名"""
        return hashlib.md5(url.encode()).hexdigest()

    def first_analyzer(self, article_url) -> None:
        """调用DeepSeek API输入背景"""
        cache_key = self._generate_cache_key(article_url)
        cached_result = self._load_from_cache(cache_key)
        if cached_result:
            return
        with open('prompt.md', 'r', encoding='utf-8')as f:
            prompt = f.read()
        first_message = {
            "role": "system",
            "content": prompt
        }
        self.message.append(first_message)
        try:
            response = self.client.chat.completions.create(
                model="deepseek-chat",
                messages=self.message
            )
        except Exception as e:
            return

    def second_analyzer(self, html, article_url) -> Dict:
        """调用DeepSeek API分析代码语法"""
        cache_key = self._generate_cache_key(article_url)
        cached_result = self._load_from_cache(cache_key)
        if cached_result:
            print(cached_result)
            return cached_result

        prompt = f"""按照之前给你的提示词分析下面的html文件{html}"""
        message = {"role": "user", "content": prompt, "web_search": True}
        if len(self.message) == 1:
            self.message.append(message)
        else:
            self.message.pop()
            self.message.append(message)

        try:
            response = self.client.chat.completions.create(
                model="deepseek-chat",
                messages=self.message
            )
            print(response.choices[0].message.content)
            res = json.loads(fr'{response.choices[0].message.content[8: -4]}')
            return res
        except Exception as e:
            return {
                "error": f"API调用失败: {str(e)}",
            }

    def save_result_to_json(self, key: str, result: Dict):
        with open(self.cache_dir / f'{key}.json', 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)

    def _load_from_cache(self, key: str) -> Optional[Dict]:
        cache_file = self.cache_dir / f'{key}.json'
        if cache_file.exists():
            with open(cache_file, 'r', encoding='utf-8')as f:
                return json.load(f)
        return None


def main():
    ds = DeepSeekCodeAnalyzer()
    # ds.analyze_html_file('test/1.md', 'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/concurrency-overview', '指南', '并发概述')
    # ds.message = []
    # ds.analyze_html_file('test/2.md', 'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/async-concurrency-overview', '指南', '异步并发 (Promise和async/await)')
    # ds.message = []
    # ds.analyze_html_file('test/3.md', 'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/multi-thread-concurrency-overview', '指南', '多线程并发概述')
    # ds.message = []
    # ds.analyze_html_file('test/4.md', 'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/taskpool-introduction', '指南', 'TaskPool简介')
    # ds.message = []
    # ds.analyze_html_file('test/5.md', 'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/worker-introduction', '指南', 'Worker简介')
    # ds.message = []
    # ds.analyze_html_file('test/6.md', 'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/taskpool-vs-worker', '指南', 'TaskPool和Worker的对比 (TaskPool和Worker)')
    # ds.message = []
    # ds.analyze_html_file('test/7.md', 'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/interthread-communication-overview', '指南', 'ArkTS线程间通信概述')
    # ds.message = []
    # ds.analyze_html_file('test/8.md', 'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/serializable-overview', '指南', '线程间通信对象概述')
    # ds.message = []
    ds.analyze_html_file('test/样例.md', 'https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/serializable-overview1', '指南', '样例')
    analyzer_results = load_json_result('.code_cache')
    write_result_excel_v2(analyzer_results)


if __name__ == '__main__':
    main()

